package com.doushu.dispatch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.doushu.dispatch.common.constans.RedisCode;
import com.doushu.dispatch.common.dto.ResultDto;
import com.doushu.dispatch.common.dto.ResultDtoFactory;
import com.doushu.dispatch.common.property.SocketProperty;
import com.doushu.dispatch.common.utils.HttpUtil;
import com.doushu.dispatch.dto.*;
import com.doushu.dispatch.mapper.ItemMapper;
import com.doushu.dispatch.mapper.KeywordZTCMapper;
import com.doushu.dispatch.service.UtilsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UtilsServiceImpl implements UtilsService {

    @SuppressWarnings("all")
    @Autowired
    private ItemMapper itemMapper;

    @SuppressWarnings("all")
    @Autowired
    private KeywordZTCMapper keywordListMapper;

    @Autowired
    private SocketProperty socketProperty;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultDto dataVer(Long shopId) {
        SimpleDateFormat df = new SimpleDateFormat("H");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int hour = Integer.parseInt(df.format(new Date()));
        DataVerDto dataVerDto = new DataVerDto();
        dataVerDto.setMin_num(500);
        dataVerDto.setMax_num(1000);
        dataVerDto.setUp_data_num(10);
        dataVerDto.setUp_data_time(100);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String startDate;
        String endDate;
        if (hour > 9 && hour < 24) {
            calendar.add(Calendar.DATE, -1);
            endDate = sdf.format(calendar.getTime());
        } else {
            calendar.add(Calendar.DATE, -2);
            endDate = sdf.format(calendar.getTime());
        }
        dataVerDto.setEnd_date(endDate);
        if (itemMapper.existsBySid(shopId) != null) {
            startDate = keywordListMapper.findMaxDateTimeBySid(shopId);
            if (startDate == null) {
                calendar.add(Calendar.DATE, -29);
                startDate = sdf.format(calendar.getTime());
            } else {
                List<Long> itemIds = itemMapper.findItemIdsBySidAndStatus(shopId, true);
                dataVerDto.setItemArr(itemIds);
                if (startDate.compareTo(endDate) < 0) {
                    try {
                        Calendar cd = new GregorianCalendar();
                        Date start = sdf.parse(startDate);
                        cd.setTime(start);
                        cd.add(Calendar.DATE, 1);
                        startDate = sdf.format(cd.getTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    dataVerDto.setDataistrue(false);
                } else {
                    dataVerDto.setDataistrue(true);
                }
            }
            dataVerDto.setFocstatus(true);
        } else {
            calendar.add(Calendar.DATE, -29);
            startDate = sdf.format(calendar.getTime());
            dataVerDto.setDataistrue(false);
            dataVerDto.setFocstatus(false);
        }
        dataVerDto.setStart_date(startDate);
        return ResultDtoFactory.toAck("success", dataVerDto);
    }

    @Override
    public ResultDto itemGetInfo(Long itemId, String type, Long shopId, String start_date, String end_date, String token, Integer force) {
        ItemGetInfoDto itemGetInfoDto = new ItemGetInfoDto();
        itemGetInfoDto.setItemId(itemId);
        itemGetInfoDto.setType(type);
        itemGetInfoDto.setShopId(shopId);
        itemGetInfoDto.setStartTime(start_date);
        itemGetInfoDto.setEndTime(end_date);
        Map<String, String> params = new HashMap<>();
        params.put("shopId", String.valueOf(shopId));
        params.put("token", token);
        params.put("type",type);
        params.put("msg", JSON.toJSONString(itemGetInfoDto));
        String json = HttpUtil.client(socketProperty.getPrefix() + socketProperty.getPush(), params);
        SocketDto<Boolean> socketDto = JSON.parseObject(json, new TypeReference<SocketDto<Boolean>>() {
        });
        if (socketDto.getRet() != 200) {
            return ResultDtoFactory.toNack("failure", false);
        }
        return ResultDtoFactory.toAck("success", true);
    }

    @Override
    public ResultDto receiveMsg(String msg) {
        ChromeDto<String> chromeDto = JSON.parseObject(msg, new TypeReference<ChromeDto<String>>() {
        });
        if(chromeDto.getType().equals("getInit")){
            chromeDto.setToken("");
        }
        if(chromeDto.getRunAsShopId()!=null&&chromeDto.getType()!=null){
            String key = RedisCode.prefix + chromeDto.getRunAsShopId() + "_" + chromeDto.getType() + "_" + chromeDto.getToken();
            System.out.println(key+":"+msg);
            stringRedisTemplate.opsForValue().set(key, msg, 300, TimeUnit.SECONDS);
        }
        return ResultDtoFactory.toAck("success", true);
    }

    @Override
    public ResultDto push(String type, Long shopId, String token, Integer campaignId, Long adGroupId, Integer firstCat, String trafficType, String crowdIds, Integer discount, Integer productId, String name, Integer onlineStatus, String startDate, String endDate) {
        PushDto pushDto = new PushDto();
        pushDto.setAdGroupId(adGroupId);
        pushDto.setCampaignId(campaignId);
        pushDto.setCrowdIds(crowdIds);
        pushDto.setDiscount(discount);
        pushDto.setEndDate(endDate);
        pushDto.setFirstCat(firstCat);
        pushDto.setName(name);
        pushDto.setOnlineStatus(onlineStatus);
        pushDto.setProductId(productId);
        pushDto.setShopId(shopId);
        pushDto.setStartDate(startDate);
        pushDto.setToken(token);
        pushDto.setTrafficType(trafficType);
        pushDto.setType(type);
        Map<String, String> params = new HashMap<>();
        params.put("shopId", String.valueOf(shopId));
        params.put("token",token);
        params.put("type",type);
        params.put("msg",JSON.toJSONString(pushDto));
        String json = HttpUtil.client(socketProperty.getPrefix() + socketProperty.getPush(),params);
        SocketDto<Boolean> socketDto = JSON.parseObject(json, new TypeReference<SocketDto<Boolean>>() {
        });
        if(socketDto.getRet() != 200){
            return ResultDtoFactory.toNack(socketDto.getMsg());
        }
        Integer num = 0;
        if(type.equals("getInit")){
            token ="";
        }
        String key = RedisCode.prefix + shopId + "_" + type + "_" + token;
        Boolean flag = true;
        String msg = null;
        Integer code = null;
        while (flag){
            if (num<200){
                if(stringRedisTemplate.hasKey(key)){
                    ChromeDto<String> chromeDto = JSON.parseObject(stringRedisTemplate.opsForValue().get(key), new TypeReference<ChromeDto<String>>() {
                    });
                    msg = chromeDto.getData();
                    code = chromeDto.getCode();
                    System.out.println(code+":"+msg);
                    stringRedisTemplate.delete(key);
                    flag = false;
                }
                num++;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                flag = false;
            }
        }
        if(code == 200){
            return ResultDtoFactory.toAck("success", JSON.parseObject(msg,new TypeReference<Object>() {}));
        }else if(code == 400){
            return ResultDtoFactory.toNack("未查询到相关信息");
        }else if(code == 404){
            return ResultDtoFactory.toNack("类型错误");
        }
        return ResultDtoFactory.toNack("出现异常");
    }

    @Override
    public ResultDto pushNotice(String head, String content) {
        PushAllDto pushAllDto = new PushAllDto();
        pushAllDto.setType("msg");
        pushAllDto.setHead(head);
        pushAllDto.setContent(content);
        Map<String, String> params = new HashMap<>();
        params.put("msg",JSON.toJSONString(pushAllDto));
        HttpUtil.client(socketProperty.getPrefix() + socketProperty.getPushAll(),params);
        return ResultDtoFactory.toAck("success",true);
    }

    @Override
    public ResultDto refreshChrome() {
        PushAllDto pushAllDto = new PushAllDto();
        pushAllDto.setType("refresh");
        Map<String, String> params = new HashMap<>();
        params.put("msg",JSON.toJSONString(pushAllDto));
        HttpUtil.client(socketProperty.getPrefix() + socketProperty.getPushAll(),params);
        return ResultDtoFactory.toAck("success",true);
    }
}
